﻿using Blm.Utils.Utility;
using Newtonsoft.Json.Linq;
using System;
using System.Threading.Tasks;
using VisionCloud.Utility.Security;

namespace VisionCloud.Utility
{
    public class AddressHelper
    {
        private static readonly string key = ConfigHelper.GetValue<string>("TencentServiceAppKey");
        private static readonly string secret_key = ConfigHelper.GetValue<string>("TencentServiceSecretKey");

        //private static readonly string domain_server = "https://apis.map.qq.com";//腾讯位置服务
        private static readonly string domain_server = "http://txmap.saas.bzlrobot-ift.com";//腾讯位置服务代理地址

        /// <summary>
        /// 腾讯位置服务地址解析接口
        /// </summary>
        private static readonly string address_api = $"/ws/geocoder/v1/";

        /// <summary>
        /// 根据坐标获取地理位置描述
        /// </summary>
        /// <param name="lat">纬度</param>
        /// <param name="lng">经度</param>
        /// <returns>地理位置描述</returns>
        public static async Task<(string Address, string Province, string City, string District, string Twon)> GetAddressFromLocation(double lat, double lng)
        {
            (string Address, string Province, string City, string District, string Town) res = (null, null, null, null, null);
            var jsonObj = await GetAsync("location", $"{lat},{lng}");
            if (jsonObj?["result"] != null)
            {
                var obj = jsonObj?["result"];
                res.Address = obj["formatted_addresses"]?["recommend"].ToString();
                var com = obj["address_component"];
                if (com != null)
                {
                    res.Province = com["province"].ToString();
                    res.City = com["city"].ToString();
                    res.District = com["district"].ToString();
                    res.Town = com["street"].ToString();
                }
            }
            return res;
        }

        /// <summary>
        /// 根据坐标获取城市名称
        /// </summary>
        /// <param name="lat">纬度</param>
        /// <param name="lng">经度</param>
        /// <returns>城市名称</returns>
        public static async Task<string> GetCityFromLocation(double lat, double lng)
        {
            var jsonObj = await GetAsync("location", $"{lat},{lng}");
            return jsonObj?["result"]?["address_component"]?["city"]?.ToString();
        }

        /// <summary>
        /// 从位置描述获取坐标
        /// </summary>
        /// <param name="address">地理位置描述</param>
        /// <returns>经纬度</returns>
        public static async Task<(float lat, float lng)> GetLocationFromAddress(string address)
        {
            var jsonObj = await GetAsync("address", address);
            var location = jsonObj?["result"]?["location"];
            var latStr = location?["lat"]?.ToString();
            var lngStr = location?["lng"]?.ToString();
            (float lat, float lng) result = (float.NaN, float.NaN);
            float.TryParse(latStr, out result.lat);
            float.TryParse(lngStr, out result.lng);
            result.lat = (float)Math.Round(result.lat, 6);
            result.lng = (float)Math.Round(result.lng, 6);
            return result;
        }

        private static async Task<JObject> GetAsync(string paramName, string paramValue)
        {
            try
            {
                var api = string.Compare(paramName, "key", true) > 0 ? $"{address_api}?key={key}&{paramName}={paramValue}" : $"{address_api}?{paramName}={paramValue}&key={key}";
                //Logger.Info($"address_api_secret_key:{api + secret_key}");
                var sig = Md5Util.GetMd5Hash(api + secret_key);
                var url = $"{domain_server}{api}&sig={sig}";
                //Logger.Info($"address_api_url:{url}");
                using var res = await HttpUtility.GetAsync(url);
                if (res == null)
                {
                    //Logger.Error($"Get请求【{url}】返回内容为空");
                    return null;
                }
                var responseStr = await res?.Content?.ReadAsStringAsync();
                //Logger.Info($"Get请求【{url}】返回内容为{responseStr}");
                return JObject.Parse(responseStr);
            }
            catch (Exception ex)
            {
                Logger.Error("腾讯位置服务地址解析接口Get请求异常：" + ex.Message, ex);
                return null;
            }
        }
    }
}